<?php


namespace App\Http\Controllers\Admin;


use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class PermissionController extends CommonController{
    private static $Permission_table='permission';
    private static $Permission_role_table='permission_role';

    public function AddPermission(Request $request){
        $roles=[
            'name' => 'required|max:10',
            'info' => 'required|max:20',
        ];
        $messages = [
            'name.required' => '权限名称不能为空',
            'name.max' => '权限名称最长十个字符',
            'info.required' => '简介不能为空',
            'info.max' => '简介最长二十个字符',
        ];
        $validator =Validator::make($request->all(),$roles,$messages);
        if ($validator->fails()) {
            return $this->ReturnJson(-1,$validator->errors()->first(),'');
        }
        $is_exit=DB::table(self::$Permission_table)
            ->where('delete_flag','=',0)
            ->where('name','=',$request->get('name'))
            ->exists();
        if ($is_exit){
            return $this->ReturnJson(-1,'权限名称重复','');
        }
        try {
            $pid=$request->get('pid')?$request->get('pid'):0;
            if ($request->get('is_show')=="1"){
                $is_show=1;
            }else{
                $is_show=0;
            }
            $insert_data=[
                'name'=>$request->get('name'),
                'info'=>$request->get('info'),
                'pid'=>$pid,
                'is_show'=>$is_show,
                'created_by'=>$this->getUserId($request->header('token')),
                'created_time'=>date('Y-m-d H:i:s',time())
            ];
           if ($request->get('route')){
               $insert_data['route']=$request->get('route');
           }
            if ($request->get('title')){
                $insert_data['title']=$request->get('title');
            }
            if ($request->get('icon')){
                $insert_data['icon']=$request->get('icon');
            }
            if ($request->get('menu_path')){
                $insert_data['menu_path']=$request->get('menu_path');
            }
            if ($request->get('menu_name')){
                $insert_data['menu_name']=$request->get('menu_name');
            }
            if ($request->get('component')){
                $insert_data['component']=$request->get('component');
            }
            DB::table(self::$Permission_table)->insert($insert_data);
            return $this->ReturnJson(200,'添加成功','');
        }catch (Exception $e){
            return $this->ReturnJson(-1,$e->getMessage(),$e->getMessage());
        }

    }

    public function GetPermission(Request $request){
        $page=$request->get('page')?$request->get('page'):self::$Page;
        $limit=$request->get('limit')?$request->get('limit'):self::$Limit;
        $res=DB::table('permission as a')
            ->where(function ($query)use ($request){
                $query->where('a.delete_flag','=',0);
                if ($request->get('val')!=null||!empty($request->get('val'))){
                    $query->where('a.name','like','%'.$request->get('val').'%');
                }
            })
            ->select('a.id','a.name','a.info','a.route','a.status','a.is_show','a.pid','a.title','a.icon','a.menu_path','a.menu_name','a.component')
            ->selectRaw('(select b.name from permission as b where b.delete_flag = 0 and b.status= 0 and b.id = a.pid) as p_name')
            ->paginate($limit,'','',$page)
            ->toArray();
        return $this->ReturnJson(200,'success',$res);
    }

    public function DelPermission(Request $request){
        $res=$request->all();
        if (!isset($res['id'])||empty($res['id'])){
            return $this->ReturnJson(-1,'参数错误','');
        }
        try {
            DB::beginTransaction();
            DB::table(self::$Permission_table)->where('id','=',$res['id'])->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            DB::table(self::$Permission_table)->where('pid','=',$res['id'])->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            //删除角色权限关系表
            DB::table(self::$Permission_role_table)->where('permission_id','=',$res['id'])->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            $per_child_list=DB::table(self::$Permission_table)->where('pid','=',$res['id'])->select('id')->get()->toArray();
            foreach ($per_child_list as $k=>$v){
                DB::table(self::$Permission_role_table)->where('permission_id','=',$v->id)->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            }
            DB::commit();
            return $this->ReturnJson(200,'删除成功','');
        }catch (Exception $e){
            DB::rollBack();
            return $this->ReturnJson(-1,'error'.$e->getMessage(),'');
        }
    }

    public function CheckPermissionShow(Request $request){
        $res=$request->all();
        if (!isset($res['status'])||!isset($res['id'])){
            return $this->ReturnJson(-1,'参数错误','');
        }
        $status=$request->get('status');
        try {
            DB::table(self::$Permission_table)->where('id','=',$res['id'])->update(['is_show'=>$status,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            return $this->ReturnJson(200,'修改成功','');
        }catch (Exception $e){
            return $this->ReturnJson(-1,'error'.$e->getMessage(),'');
        }
    }

    public function CheckPermissionStatus(Request $request){
        $res=$request->all();
        if (!isset($res['status'])||!isset($res['id'])){
            return $this->ReturnJson(-1,'参数错误','');
        }
        $status=$request->get('status');
        try {
            DB::table(self::$Permission_table)->where('id','=',$res['id'])->update(['status'=>$status,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            return $this->ReturnJson(200,'修改成功','');
        }catch (Exception $e){
            return $this->ReturnJson(-1,'error'.$e->getMessage(),'');
        }
    }
    public function UpdatePermission(Request $request){
        $res=$request->all();
        $res=json_decode($res['res'],true);

        $roles=[
            'name' => 'required|max:10',
            'info' => 'required|max:20',
            'id' => 'required',
            'pid' => 'required'
        ];
        $messages = [
            'name.required' => '权限名称不能为空',
            'name.max' => '权限名称最长十个字符',
            'info.required' => '简介不能为空',
            'info.max' => '简介最长二十个字符',
            'id.required' => '参数错误',
            'pid.required' => '参数错误',
        ];
        $validator =Validator::make($res,$roles,$messages);
        if ($validator->fails()) {
            return $this->ReturnJson(-1,$validator->errors()->first(),'');
        }

        $is_exit_role=DB::table(self::$Permission_table)
            ->where('delete_flag','=',0)
            ->where('name','=',$res['name'])
            ->where('id','<>',$res['id'])
            ->exists();
        if ($is_exit_role){
            return $this->ReturnJson(-1,'角色名称重复','');
        }

        $id=$res['id'];
        $res['created_time']=date('Y-m-d H:i:s',time());
        try {
            unset($res['p_name']);
            unset($res['id']);
            $res['update_by']=$this->getUserId($request->header('token'));
            $res['update_time']=date('Y-m-d H:i:s',time());
            DB::table(self::$Permission_table)->where('id','=',$id)->update($res);
            return $this->ReturnJson(200,'更新成功','');
        }catch (Exception $e){
            return $this->ReturnJson(-1,'error'.$e->getMessage(),'');
        }
    }

    public function getPermissionOption(){
        $res=DB::table(self::$Permission_table)
            ->where('delete_flag','=','0')
            ->where('status','=','0')
            ->select('id','name')
            ->get()
            ->toArray();
        return $this->ReturnJson(200,'success',$res);
    }

    //获取树状权限
    public function GetPermissionTree(){
        $res=DB::table(self::$Permission_table)
            ->where('delete_flag','=','0')
            ->where('status','=','0')
            ->select('id','name','info','pid','route')
            ->get()
            ->toArray();
        $list=$this->GetTree($res);
        return $this->ReturnJson(200,'success',$list);
    }

    private function GetTree($data,$pid = 0){
        $child = [];   // 定义存储子级数据数组
        foreach ($data as $key => $value) {
            if ($value->pid == $pid) {
                unset($data->$key);  // 使用过后可以销毁
                $value->child = $this->GetTree($data,$value->id);   // 递归调用，查找当前数据的子级
                $child[] = $value;   // 把子级数据添加进数组
            }
        }
        return $child;
    }

}
